#!groovy
pipeline {
  agent any
  stages {
    stage('初始化') {
      steps {
        echo "【信息】打印环境变量初始值"
        sh "printenv"

        echo "【信息】Job全部参数：${params}"

        script {
          Common = load './common/common.groovy'
          Common.applicationRootAbsolute = Common.getApplicationRootAbsolute(params.APPLICATION_ROOT_DIR)
        }

        // 拉取部署文件
        dir(Common.pipelineCicdDir) {
          git env.GIT_URL
        }

        // 拉取应用代码，需要安装插件git parameter
        git branch: params.APPLICATION_GIT_BRANCH, url: params.APPLICATION_GIT_URL

        dir(Common.applicationRootAbsolute) {
          script {
            Common.cicdYamlData = Common.readCicdYaml(params.ENV_OPTION, Common.applicationRootAbsolute)
          }
        }
      }
    }

    stage('编译') {
      steps {
        dir(Common.applicationRootAbsolute) {
          echo "【信息】开始编译"
          sh """
            if [ ${params.INSTALL} == true ];then
                cnpm install
            fi
            cnpm run build
          """
        }
      }
    }

    stage("部署") {
      steps {
        dir(Common.applicationRootAbsolute) {
          echo "【信息】开始部署"
          script {
            for (int i = 0; i < Common.cicdYamlData.envData.ipArr.length; i++) {
              def serverIp = Common.cicdYamlData.envData.ipArr[i]
              sh """
                ssh root@${serverIp} "mkdir -p /usr/share/nginx/html/${Common.cicdYamlData.applicationName};
                    rm -rf /usr/share/nginx/html/${Common.cicdYamlData.applicationName}/*";
                scp -r ./dist/* root@${serverIp}:/usr/share/nginx/html/${Common.cicdYamlData.applicationName}/;
                ssh root@${serverIp} /usr/sbin/nginx -s reload;
               """
            }
          }
        }
      }
    }

  }
  post {
    success {
      script {
        if (Common.cicdYamlData.notice.wx.ciSuccessSend || Common.cicdYamlData.notice.wx.cdSuccessSend) {
          Common.curlWx(Common.cicdYamlData.notice.wx.key, env.JOB_NAME, null, true)
        }
      }
    }
    failure {
      script {
        if (Common.cicdYamlData.notice.wx.ciFailureSend || Common.cicdYamlData.notice.wx.cdFailureSend) {
          Common.curlWx(Common.cicdYamlData.notice.wx.key, env.JOB_NAME, null, false)
        }
      }
    }
  }
}

